package br.ufrj.dcc.xml.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import br.ufrj.dcc.xml.dynamicintervals.encoding.DriverNotFoundException;

public class DatabaseManager {

	private DatabaseSettings settings;

	private Connection defaultConnection;

	public StringBuffer outputText = new StringBuffer();

	public DatabaseManager(DatabaseSettings settings) {
		super();
		this.settings = settings;
	}

	public void testDriver() {
		try {
			Class.forName(getSettings().getDriverClass());
		} catch (ClassNotFoundException e) {
			throw new DriverNotFoundException(e);
		}
	}

	public Connection getNewConnection() throws SQLException {
		if (defaultConnection != null && !defaultConnection.isClosed())
			defaultConnection.close();
		return getDefaultConnection();
	}

	public Connection getDefaultConnection() throws SQLException {
		if (defaultConnection == null || defaultConnection.isClosed()) {
			defaultConnection = DriverManager.getConnection(getSettings()
					.getUrl(), getSettings().getUser(), getSettings()
					.getPassword());
		}
		return defaultConnection;
	}

	public PreparedStatement createPreparedStatement(String sql)
			throws SQLException {
		return getDefaultConnection().prepareStatement(sql);
	}

	public Statement createStatement() throws SQLException {
		return getDefaultConnection().createStatement();
	}

	public DatabaseSettings getSettings() {
		return settings;
	}

	public void setSettings(DatabaseSettings settings) {
		this.settings = settings;
	}

	public String getOutputText() {
		return outputText.toString();
	}

}
